package BNS.plumbing;

import java.io.File;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;


/** The class that is invoked from the command line to initiate the 
	BNS SessionHost services. 
	TODO: move this into the SessionHost class?
	*/
public class Server {
	
	/** The program to invoke in order to start the whole BNS server.
		This program takes no command-line arguments, but two system properties will
		be examined:<ul> 
		<li>PREP, which  specifies the path to a directory where the Library will 
			initially search for prepared files (GraphPacks and games)</li>
		<li>ARCH, which  specifies the path to a directory where the Library will 
			place the sessionLog and the gameLogs.</li>
		</ul>
		The following is an example command line invocation: <code><br/><br/>
java -ea \<br/>
	-cp $BNSCLASSES \<br/>
	-Djava.rmi.server.codebase=http://JSJlaptop.local/~sjudd/BNS/classes/ \<br/>
	-Djava.security.policy=$HOME/Documents/netSci/software/BNS/RMI.policy \<br/>
	-DPREP=/Users/sjudd/Documents/netSci/software/prepped \<br/>
	-DARCH=/Users/sjudd/Documents/netSci/software/output \<br/>
	BNS.plumbing.Server <br/>
		</code>
		*/
	public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
			System.setSecurityManager(new RMISecurityManager());
			}
		try {
	    if (args.length==0) {
	      System.err.println("argument must be the name of the current session!");
	      System.exit(01);
	    }
			SessionHost sh = new SessionHost(args[0]);
			System.err.println("created an instance of "+ sh.getClass()+" as server");
			//Registry reg= LocateRegistry.getRegistry("localhost",1099);
			Registry reg= LocateRegistry.createRegistry(1099);
			reg.rebind(Constants.serviceName, sh);
			System.err.println(Constants.serviceName+" server ready.");
			
			/* This method must be called before using the Library. It initializes a 
			FileChooser using the PREP property for the storage and retrieval of games.*/
			String prep= System.getProperty("PREP");
			if (prep==null) prep= "./";
			Library.setPrep(new File(prep));
			/* We discover the value of the ARCH property, which will be used
			in the Library for storing session files and exp files. */
			String arch= System.getProperty("ARCH");
			if (arch==null) arch= "./output";
			Library.setArch(new File(arch));
			
			sh.run();
			System.err.println("shutting down server");
			reg.unbind(Constants.serviceName);
			UnicastRemoteObject.unexportObject(sh, true);
			}
		catch (RemoteException rex) {
			System.err.println("Remote Exception in BNSServer: " + rex);
			rex.printStackTrace();
			}
		catch (java.rmi.NotBoundException ex) {
			System.err.println("Something munged up the registry " + ex);
			}
		}
	
	}
